#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<stack>

class Node {
public:
    int val;
    Node* left;
    Node* right;

    Node() {}

    Node(int _val) {
        val = _val;
        left = NULL;
        right = NULL;
    }

    Node(int _val, Node* _left, Node* _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};

Node* treeToDoublyList(Node* root) {
    if (root == NULL)  return root;
    Node* listHead = NULL;
    Node* listLastNode = NULL;
    stack<Node*> s;
    while (s.size() || root) {
        while (root)
        {
            s.push(root);
            root = root->left;
        }
        root = s.top();
        s.pop();
        if (listHead == NULL) {
            listHead = root;
        }
        else {
            listLastNode->right = root;
            root->left = listLastNode;
        }
        listLastNode = root;
        root = root->right;
    }
    listHead->left = listLastNode;
    listLastNode->right = listHead;
    return listHead;
}

//Node* pre, * head;
//Node* treeToDoublyList(Node* root) {
//    if (root == nullptr) return nullptr;
//    dfs(root);
//    head->left = pre;
//    pre->right = head;
//    return head;
//}
//
//void dfs(Node* cur) {
//    if (cur == nullptr)  return;
//    dfs(cur->left);
//    if (head == nullptr) head = cur;
//    else pre->right = cur;
//    cur->left = pre;
//    pre = cur;
//    dfs(cur->right);
//}